package org.backend.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.backend.pojo.entity.Product;
import org.backend.pojo.vo.UserCartVO;
import org.backend.pojo.entity.Cart;
import org.backend.repository.CartRepository;
import org.backend.repository.ProductRepository;
import org.backend.service.CartService;
import org.backend.utils.ApiResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private ProductRepository productRepository;

    @Override
    public ApiResponse<List<UserCartVO>> getUserCart(Cart c) {
        List<UserCartVO> cartDTOs = new ArrayList<>();
        List<Cart> carts = new ArrayList<>();
        if (c.getUserId() != null) {
            carts = cartRepository.getUserCart(c.getUserId());

        } else if (c.getOpenid() != null) {
            carts = cartRepository.getUserCartByOpenId(c.getOpenid());
        }
        for (Cart cart : carts) {
            UserCartVO userCartVO = new UserCartVO();
            Product product = productRepository.getProductById(cart.getProductId());
            BeanUtils.copyProperties(cart, userCartVO);
            BeanUtils.copyProperties(product, userCartVO);

            cartDTOs.add(userCartVO);
        }
        return ApiResponse.success(cartDTOs);
    }

    @Override
    public ApiResponse<String> add(Cart cart) {
        if (cart.getQuantity() == null) { // 考虑到小程序端的物品添加问题
            cart.setQuantity(1);
        }
        if (cartRepository.add(cart) > 0) {
            return ApiResponse.success("添加成功");
        }
        return ApiResponse.error("添加失败");
    }

    @Override
    public ApiResponse<String> remove(Cart cart) {
        if (cartRepository.remove(cart) > 0) {
            return ApiResponse.success("删除成功");
        }
        return ApiResponse.error("删除异常");
    }

    @Override
    public ApiResponse<String> addProduct(Cart cart) {
        if (cartRepository.addProduct(cart) > 0) {
            return ApiResponse.success("添加成功");
        }
        return ApiResponse.error("添加失败");
    }

    @Override
    public ApiResponse<String> subProduct(Cart cart) {
        if (cart.getQuantity() > 1 && cartRepository.subProduct(cart) > 0) {
            return ApiResponse.success("添加成功");
        }
        return ApiResponse.error("添加失败");
    }
}
